package face.pay.common.enterprise.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import face.pay.common.enterprise.service.IWeChatMchUpgradeInfoService;
import face.pay.dao.*;
import face.pay.entity.*;
import face.pay.server.IServerAddressServer;
import face.pay.util.FaceFileUtils;
import face.pay.util.HttpClientUtil;
import face.pay.util.ResultMessage;
import face.pay.util.ValidatorUtil;
import face.pay.util.bean.JavaBeanUtils;
import face.pay.util.page.PageData;
import face.pay.util.page.PageParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class WeChatMchUpgradeInfoService implements IWeChatMchUpgradeInfoService {

    @Autowired
    private WeChatMchInfoUpgradeDao weChatMchInfoUpgradeDao;

    @Autowired
    private MchApplymentInfoDao mchApplymentInfoDao;

    @Autowired
    private IServerAddressServer iServerAddress;

    @Autowired
    private OemConfigInfoDao oemConfigInfoDao;

    @Autowired
    private EnterpriseInfoDao enterpriseInfoDao;

    @Autowired
    private MchApplymentUpgradeInfoDao mchApplymentUpgradeInfodao;


    @Transactional
    @Override
    public WeChatMchUpgradeInfo getByUserId(Integer userId, Integer oemId, Integer agencyId) {
        WeChatMchUpgradeInfo info = this.weChatMchInfoUpgradeDao.queryByUserId(userId);
        if (info == null) {
            WeChatMchUpgradeInfo record = new WeChatMchUpgradeInfo();
            EnterpriseInfo parm = this.enterpriseInfoDao.queryByUserId(userId);
            if (StringUtils.isNotBlank(parm.getWxSubMchId())) {
                record.setSub_mch_id(parm.getWxSubMchId());
                record.setUserId(userId);
                record.setOemId(oemId);
                record.setCreatedBy(agencyId);
                record.setUpdatedBy(agencyId);
                this.weChatMchInfoUpgradeDao.insert(record);
                return record;
            } else {
                return new WeChatMchUpgradeInfo();
            }
        } else {
            return info;
        }
    }


    /**
     * 物料上传
     *
     * @param weChatMchUpgradeInfo
     * @param bytes
     * @param fileName
     * @param keyName
     * @param loginUser
     * @return
     */
    @Override
    public ResultMessage mediaload(WeChatMchUpgradeInfo weChatMchUpgradeInfo, byte[] bytes, String fileName, String keyName, UserInfo loginUser) throws Exception {
        if (weChatMchUpgradeInfo.getId() == null) {
            return ResultMessage.createFail("小微商户进件成功才能进行升级操作!");
        }

        Integer oemId = loginUser.getOemId();

        OemConfigInfo configInfo = this.oemConfigInfoDao.getByOemId(oemId);

        String faceKey = configInfo.getFaceKey();

        String hash = DigestUtils.md5DigestAsHex(bytes);

        String fileBody = FaceFileUtils.byte2hex(bytes);


        Map<String, Object> map = new HashMap<>();

        map.put("oemId", String.valueOf(oemId));

        Map<String, String> data = new HashMap<>();
        data.put("fileName", fileName);
        data.put("body", fileBody);
        data.put("userId", String.valueOf(weChatMchUpgradeInfo.getUserId()));

        String sign = WXPayUtil.generateSignature(data, faceKey, WXPayConstants.SignType.MD5);
        map.put("sign", sign);
        map.put("data", data);

        String json = JSON.toJSONString(map);

        String resultMessae = HttpClientUtil.doPostJson(iServerAddress.getFileUploadUrl(), json);

        log.info(resultMessae);
        if (StringUtils.isNotBlank(resultMessae)) {

            ResultMessage resultMessage = JSON.parseObject(resultMessae, ResultMessage.class);

            if (new Integer(1).equals(resultMessage.getCode())) {

                /**
                 * 更新物料信息
                 */
                Map<String, String> resultMap = (Map<String, String>) resultMessage.getData();

                Map<String, Object> param = new HashMap<>();

                param.put("id", weChatMchUpgradeInfo.getId());
                param.put(keyName, resultMap.get("media_id"));
                this.weChatMchInfoUpgradeDao.updateImg(param);

            }
            return resultMessage;
        } else {
            return ResultMessage.createFail("调用链接失败");

        }
    }


    @Override
    public ResultMessage modifyInfo(WeChatMchUpgradeInfo weChatMchUpgradeInfo, UserInfo loginUser) {
        if (weChatMchUpgradeInfo.getId() == null) {
            return ResultMessage.createFail("小微商户进件成功才能进行升级操作!");
        }
        this.weChatMchInfoUpgradeDao.update(weChatMchUpgradeInfo);
        return ResultMessage.createSuccess("编辑成功!");
    }

    /**
     * 进件提交
     *
     * @param weChatMchUpgradeInfo
     * @param loginUser
     * @return
     */
    @Override
    @Transactional
    public ResultMessage subinfo(WeChatMchUpgradeInfo weChatMchUpgradeInfo, UserInfo loginUser) throws Exception {

        if (weChatMchUpgradeInfo.getId() == null) {
            return ResultMessage.createFail("小微商户进件成功才能进行升级操作!");
        }
        Integer oemId = loginUser.getOemId();

        log.info("小微商户升级进件提交id:{}", weChatMchUpgradeInfo.getUserId());

        MchApplymentUpgradeInfo applyrecord = new MchApplymentUpgradeInfo();
        applyrecord.setOemId(oemId);
        applyrecord.setUserId(weChatMchUpgradeInfo.getUserId());
        List<MchApplymentUpgradeInfo> list = this.mchApplymentUpgradeInfodao.queryList(applyrecord);

        /**
         * 判断重复提交
         */
        if (list.size() > 0) {
            MchApplymentUpgradeInfo apply = list.get(0);
            String state = apply.getApplyment_state();

            if (!("REJECTED".equals(state) || "FROZEN".equals(state))) {
                return ResultMessage.createFail("最近提交的申请未处理或已通过请勿重复提交");
            }
        }

        /**
         * 默认提交保存最新信息
         */
        this.weChatMchInfoUpgradeDao.update(weChatMchUpgradeInfo);

        OemConfigInfo configInfo = this.oemConfigInfoDao.getByOemId(oemId);

        String faceKey = configInfo.getFaceKey();

        MchApplymentUpgradeInfo mchApplymentInfo = new MchApplymentUpgradeInfo();

        BeanUtils.copyProperties(weChatMchUpgradeInfo, mchApplymentInfo);

        /**
         * 排除ID 字段
         */
        mchApplymentInfo.setId(null);
        /**
         * 验证非空
         */

        Map<String, StringBuffer> validateMap = ValidatorUtil.validate(mchApplymentInfo);

        if (validateMap.isEmpty()) {
            Map<String, Object> param = new HashMap<>();

            Map<String, String> data = JavaBeanUtils.toMap(mchApplymentInfo);
            data.put("userId", String.valueOf(mchApplymentInfo.getUserId()));
            data.put("omId", String.valueOf(oemId));

            String sign = WXPayUtil.generateSignature(data, faceKey);

            param.put("data", data);
            param.put("oemId", oemId);
            param.put("sign", sign);

            String json = JSON.toJSONString(param);

            /**
             * 发送给 开放接口
             */

            log.info("发送数据到开放接口中心:" + json);

            String resultMessae = HttpClientUtil.doPostJson(iServerAddress.getMchApplyUpgradeUrl(), json);

            log.info("开放接口中心返回数据:" + resultMessae);

            if (StringUtils.isNotBlank(resultMessae)) {

                ResultMessage resultMessage = JSON.parseObject(resultMessae, ResultMessage.class);

                return resultMessage;
            } else {
                return ResultMessage.createFail("调用链接失败");

            }

        } else {
            return ResultMessage.createFail("资料信息不全", validateMap);

        }


    }


    /**
     * 分页查询升级进件列表
     *
     * @param apply
     * @param pageParam
     * @param loginUser
     * @return
     */
    @Override
    public PageData queryPage(MchApplymentUpgradeInfo apply, PageParam pageParam, UserInfo loginUser) {
        PageHelper.startPage(pageParam.getPageNo(), pageParam.getPageSize());

        List<MchApplymentUpgradeInfo> applymentInfos = this.mchApplymentUpgradeInfodao.queryList(apply);

        PageInfo<MchApplymentUpgradeInfo> pageInfo = new PageInfo<>(applymentInfos);

        PageData<MchApplymentUpgradeInfo> pageData = new PageData<>(pageInfo.getTotal(), applymentInfos);

        return pageData;
    }
}
